/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.ddtroops.serviceclasses;

import cz.muni.fi.pa165.ddtroops.daointerfaces.UserDAO;
import cz.muni.fi.pa165.ddtroops.dto.DTOFactory;
import cz.muni.fi.pa165.ddtroops.dto.UserDTO;
import cz.muni.fi.pa165.ddtroops.entities.EntityBuilder;
import cz.muni.fi.pa165.ddtroops.entities.User;
import cz.muni.fi.pa165.ddtroops.serviceinterfaces.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Svoboda
 */
@Service
@Qualifier("userService")
public class UserServiceImpl implements UserService {

    @Autowired(required=true)
    private UserDAO dao;

    public void setDao(UserDAO dao) {
        this.dao = dao;
    }

    @Transactional
    public UserDTO createNewUser(String name, String password, String authority)
    {

        User u = new EntityBuilder<User>(User.class)
                .withProperty("Name", name)
                .withProperty("Password", password)
                .withProperty("Authority", authority)
                .Build();

        return DTOFactory.createUserDTO(u);
    }

    @Transactional
    public void create(UserDTO userDTO)
    {
        dao.create(DTOFactory.createUser(userDTO));
    }

    @Transactional
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void update(UserDTO userDTO)
    {
        dao.update(DTOFactory.createUser(userDTO));
    }

    @Transactional
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void delete(UserDTO userDTO)
    {
        dao.delete(DTOFactory.createUser(userDTO));
    }

    @Transactional(readOnly=true)
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public UserDTO getByName(String name)
    {
        List<User> l = dao.getAll();
        for (User u : l) {
            if(u.getName().equals(name)) return DTOFactory.createUserDTO(u);
        }
        return null;
    }

    @Transactional(readOnly=true)
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public UserDTO getById(Long id)
    {
        User u = dao.getById(id);
        return (u!=null)?DTOFactory.createUserDTO(u):null;
    }

    @Transactional(readOnly=true)
    public List<UserDTO> getAll()
    {
        List<UserDTO> us = new ArrayList<UserDTO>();
        for (User u : dao.getAll()) {
            us.add(DTOFactory.createUserDTO(u));
        }
        return us;
    }
}
